package com.eastedu.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eastedu.converter.BasicResourceKnowledgeConverter;
import com.eastedu.model.basic.ResourceFile;
import com.eastedu.model.ktree.BasicResourceKnowledgeJsonSerializableDTO;
import com.eastedu.repository.basic.ResourceSource;
import com.eastedu.repository.basic.mapper.BasicResourceFileMapper;
import com.eastedu.repository.basic.mapper.BasicResourceKnowledgeMapper;
import com.eastedu.repository.basic.mapper.BasicResourceMapper;
import com.eastedu.repository.basic.mapper.ResourceSourceMapper;
import com.eastedu.repository.basic.po.BasicResourceFilePO;
import com.eastedu.repository.basic.po.BasicResourceKnowledgePO;
import com.eastedu.repository.basic.po.BasicResourcePO;
import com.eastedu.superise.handler.common.model.ApplyUserExcelModel;
import com.eastedu.utils.JsonUtil;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * The type Basic resource manager.
 *
 * @author zhangzhishuai
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BasicResourceManagerImpl implements BasicResourceManager, ApplyUserManager {

    public static final List<String> RESOURCE_TYPE_NAMES = Lists.newArrayList("备课实录", "教案", "教学课件", "普通实录");
    private final BasicResourceMapper basicResourceMapper;
    private final ResourceSourceMapper resourceSourceMapper;
    private final BasicResourceFileMapper basicResourceFileMapper;
    private final BasicResourceKnowledgeMapper basicResourceKnowledgeMapper;
    private final BasicResourceKnowledgeConverter basicResourceKnowledgeConverter;

    @Override
    public void updateFileJsonByResourceId(String basicResourceId) {
        List<BasicResourceFilePO> pos = basicResourceFileMapper.selectList(Wrappers.<BasicResourceFilePO>lambdaQuery().eq(BasicResourceFilePO::getBasicResourceId, basicResourceId));
        this.updateFileJsonByResourceId(basicResourceId, pos);
    }

    @Override
    public void updateFileJsonByResourceId(String basicResourceId, List<BasicResourceFilePO> pos) {
        List<ResourceFile> files = pos.parallelStream().map(BasicResourceFilePO::toFile).collect(Collectors.toList());
        basicResourceMapper.updateFilesJson(basicResourceId, JSON.toJSONString(files));
    }

    @Override
    public void updateKnowledgeJsonByResourceId(String basicResourceId) {
        List<BasicResourceKnowledgePO> pos = basicResourceKnowledgeMapper.selectList(Wrappers.<BasicResourceKnowledgePO>lambdaQuery()
                .eq(BasicResourceKnowledgePO::getBasicResourceId, basicResourceId));
        this.updateKnowledgeJsonByResourceId(basicResourceId, pos);
    }

    @Override
    public void updateKnowledgeJsonByResourceId(String basicResourceId, List<BasicResourceKnowledgePO> pos) {
        List<BasicResourceKnowledgeJsonSerializableDTO> knowledgeJsonSerializableDTOList = pos.parallelStream()
                .map(basicResourceKnowledgeConverter::toSerializableDTO).collect(Collectors.toList());
        basicResourceMapper.updateKnowledgeJson(basicResourceId, JSON.toJSONString(knowledgeJsonSerializableDTOList));
    }

    @Override
    public void updateApplyUserId(BasicResourcePO po, Integer newApplyUserId, String newApplyUserName, Integer existedApplyUserId) {
        AtomicInteger updateCount = new AtomicInteger(0);
        if (Objects.equals(po.getCreateUserid(), existedApplyUserId)) {
            po.setCreateUserid(newApplyUserId);
            po.setCreateUserName(newApplyUserName);
            updateCount.incrementAndGet();
        }
        List<ResourceSource> resourceSources = JsonUtil.parseList(po.getSourcesJson(), ResourceSource.class);
        resourceSources.forEach(item -> {
            if (item.getProvider().equals(existedApplyUserId)) {
                item.setProvider(newApplyUserId);
                item.setProviderName(newApplyUserName);
                updateCount.incrementAndGet();
            }
        });
        if (updateCount.get() == 0) {
            log.warn("更新应用者失败，未找到匹配的记录，resourceId:{}, existedApplyUserId:{}", po.getId(), existedApplyUserId);
            return;
        }
        po.setSourcesJson(CollectionUtil.isEmpty(resourceSources) ? null : JsonUtil.toJsonString(resourceSources));
        resourceSourceMapper.updateProvider(existedApplyUserId, newApplyUserId, po.getId());
        basicResourceMapper.updateSourceJsonAndProviderByResourceId(po, po.getId().toString());
    }

    @Override
    public boolean supports(String resourceTypeName) {
        return RESOURCE_TYPE_NAMES.contains(resourceTypeName);
    }

    @Override
    public void updateApplyUserId(ApplyUserExcelModel applyUserExcelModel) {
        BasicResourcePO po = this.basicResourceMapper.selectById(applyUserExcelModel.getResourceId());
        this.updateApplyUserId(po, applyUserExcelModel.getNewCreateUserId(), applyUserExcelModel.getNewCreateUserName(), applyUserExcelModel.getCreateUserId());
    }
}
